package com.sunshuo.springsecuritydemo.dao;

import com.sunshuo.springsecuritydemo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName UserDao
 * @Description
 * @Author sunshuo
 * @Date 2021/11/6 20:11
 */
@Repository
public class UserDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 根据用户名查询用户信息
     * @param userName 用户名
     * @return
     */
    public User findUserByUsername(String userName) {
        String sql = "select * from t_user where username = ?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                return readUser(rs);
            }
        }, userName);
    }

    public List<User> getUsers() {
        String sql = "select * from t_user";
        List<User> users = jdbcTemplate.query(sql, (rs, rowNum) -> readUser(rs));
        return users;
    }

    private User readUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getString("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setFullname(rs.getString("fullname"));
        user.setDel(rs.getInt("is_del") == 1);
        return user;
    }

}
